package com.example.peibei.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.blankj.utilcode.util.ToastUtils;
import com.dingtao.common.MyActivity;
import com.dingtao.common.bean.AppVersion;
import com.dingtao.common.bean.PayPower;
import com.dingtao.common.bean.User;
import com.dingtao.common.core.DataCall;
import com.dingtao.common.core.IWDApplication;
import com.dingtao.common.core.WDActivity;
import com.dingtao.common.core.exception.ApiException;
import com.dingtao.common.util.DownloadUtils;
import com.dingtao.common.util.SPUtils;
import com.dingtao.common.util.StringUtils;
import com.dingtao.common.util.UIUtils;
import com.example.peibei.BuildConfig;
import com.example.peibei.R;
import com.example.peibei.base.Constant;
import com.example.peibei.base.SpConstant;
import com.example.peibei.bean.CityBean;
import com.example.peibei.bean.SpUserInfoCall;
import com.example.peibei.service.presenter.AppVersionPresenter;
import com.example.peibei.service.presenter.GetImMessagePresenter;
import com.example.peibei.service.presenter.GetImUnreadPresenter;
import com.example.peibei.service.presenter.PayPowerPresenter;
import com.example.peibei.service.presenter.UserInfoPresenter;
import com.example.peibei.service.presenter.UserSigPresenter;
import com.example.peibei.ui.fragment.ChatFragment;
import com.example.peibei.ui.fragment.GuangChangFragment;
import com.example.peibei.ui.fragment.HomeFragmentThree;
import com.example.peibei.ui.fragment.MeFragment;
import com.example.peibei.ui.fragment.PaiDanFragment;
import com.example.peibei.ui.fragment.SquareFragment;
import com.example.peibei.ui.utils.NotificationManagerUtils;
import com.example.peibei.ui.weight.CEditText;
import com.example.peibei.ui.weight.CenterDialog;
import com.facebook.common.internal.Supplier;
import com.facebook.common.util.ByteConstants;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.cache.MemoryCacheParams;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.linxiao.framework.dialog.BottomDialog;
import com.liulishuo.magicprogresswidget.MagicProgressBar;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMConversation;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMUserFullInfo;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuikit.tuiconversation.ui.page.TUIConversationFragment;
import com.yxp.permission.util.lib.PermissionUtil;
import com.yxp.permission.util.lib.callback.PermissionResultCallBack;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import lombok.val;
import me.jessyan.progressmanager.body.ProgressInfo;

@Route(path = Constant.ACTIVITY_URL_MAIN)
public class MainActivity extends WDActivity implements RadioGroup.OnCheckedChangeListener {

    @BindView(R.id.bottom_menu)
    RadioGroup bottomMenu;
    @BindView(R.id.cart_btn)
    RadioButton cart_btn;
    @BindView(R.id.chat_btn)
    RadioButton chat_btn;
    @BindView(R.id.vp_home)
    ViewPager vp_home;
    @BindView(R.id.tv_count_three)
    TextView tv_count_three;

    //    HomeFragment homeFragment;
    HomeFragmentThree homeFragment;
    Fragment squareFragment;
    ChatFragment chatFragment;
    MeFragment meFragment;
    Fragment currentFragment;
    private SPUtils spUtils;
    private String token;
    private String userSig;
    private UserInfoPresenter userInfoPresenter;
    private AppVersionPresenter appVersionPresenter;
    private long mid;
//    private boolean isIdentity;
    private long exitTime = 0;
    private boolean isAgree = false;
    private String headUrl;
    //声明AMapLocationClient类对象
    private CenterDialog bottomDialog;
    private ProgressBar progress_bar;
    private TextView tv_updating;
    private GetImUnreadPresenter getImUnreadPresenter;
    private GetImMessagePresenter getImMessagePresenter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        changeStatusBar(0);
        spUtils = new SPUtils(MainActivity.this, SpConstant.USER_TOKEN);
        isAgree = spUtils.getBoolean(SpConstant.USER_AGREE);
        userInfoPresenter = new UserInfoPresenter(new UserInfoCall());
        appVersionPresenter = new AppVersionPresenter(new VersionCall());
        getImUnreadPresenter = new GetImUnreadPresenter(new ImUnreadCall());
        getImMessagePresenter = new GetImMessagePresenter(new ImMessageCall());
        if (!isAgree) {
            showAgreeDialog();
        } else {
            initApplication();
//            getPermission();
            initData();
        }
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
//        StatusBarUtil.setTranslucentForImageViewInFragment(MainActivity.this, null);
    }

    private void initApplication() {
        TUILogin.init(this, 1400572052, null, null);//初始化im
        JPushInterface.setDebugMode(BuildConfig.DEBUG);
        JPushInterface.init(this);
        Fresco.initialize(this, getConfigureCaches(this));//图片加载框架初始化

        //IM或者推送等服务的appliation初始化
        loadModuleApp();
    }

    private static int MAX_MEM = 30 * ByteConstants.MB;

    /**
     * 加载各个模块的Application，例如：推送和IM等模块都需要有Application，
     * 但组件化只能有一个Application，而且为了解耦各个模块不能互相引用，
     * 所以只能通过反射方式，把这些module_appliation进行初始化
     */
    private void loadModuleApp() {
        for (String moduleImpl : IWDApplication.MODULE_APP) {
            try {
                Class<?> clazz = Class.forName(moduleImpl);
                Object obj = clazz.newInstance();
                if (obj instanceof IWDApplication) {
                    ((IWDApplication) obj).onCreate(getApplication());
                }
            } catch (Exception e) {
            }
        }
    }

    private ImagePipelineConfig getConfigureCaches(Context context) {
        final MemoryCacheParams bitmapCacheParams = new MemoryCacheParams(
                MAX_MEM,// 内存缓存中总图片的最大大小,以字节为单位。
                Integer.MAX_VALUE,// 内存缓存中图片的最大数量。
                MAX_MEM,// 内存缓存中准备清除但尚未被删除的总图片的最大大小,以字节为单位。
                Integer.MAX_VALUE,// 内存缓存中准备清除的总图片的最大数量。
                Integer.MAX_VALUE);// 内存缓存中单个图片的最大大小。

        Supplier<MemoryCacheParams> mSupplierMemoryCacheParams = new Supplier<MemoryCacheParams>() {
            @Override
            public MemoryCacheParams get() {
                return bitmapCacheParams;
            }
        };
        ImagePipelineConfig.Builder builder = ImagePipelineConfig.newBuilder(context);
        builder.setBitmapMemoryCacheParamsSupplier(mSupplierMemoryCacheParams);
        return builder.build();
    }

    private void initData() {
//        EventBus.getDefault().register(this);
        bottomMenu.setOnCheckedChangeListener(this);
        homeFragment = new HomeFragmentThree();
        squareFragment = new GuangChangFragment();
//        squareFragment = new PaiDanFragment();
        chatFragment = new ChatFragment();
        meFragment = new MeFragment();
        currentFragment = homeFragment;
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.add(R.id.container, homeFragment)
                .show(homeFragment).commit();
        cart_btn.setOnClickListener(v -> {
            token = spUtils.getString(SpConstant.USER_TOKEN);
            if (TextUtils.isEmpty(token)) {
                intent(LoginActivity.class);
            } else {
                showDialog();
            }
        });
        chat_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(token)) {
                    intent(LoginActivity.class);
                    chat_btn.setChecked(false);
                } else {
                    chat_btn.setChecked(true);
                }
            }
        });
        appVersionPresenter.reqeust("");
    }

    @Override
    protected void onResume() {
        super.onResume();
        isAgree = spUtils.getBoolean(SpConstant.USER_AGREE);
        token = spUtils.getString(SpConstant.USER_TOKEN);
        userSig = spUtils.getString(SpConstant.USER_SIG);
        mid = spUtils.getLong(SpConstant.USER_MID);
        if (!TextUtils.isEmpty(token) && isAgree) {
            userInfoPresenter.reqeust("Bearer " + token);
        }
    }

    private void getUnReadMessage() {
        V2TIMConversation v2TIMConversation = new V2TIMConversation();
        int unreadCount = v2TIMConversation.getUnreadCount();
        Log.i("answer", unreadCount + "条未读消息");
        if (unreadCount > 0) {
            tv_count_three.setVisibility(View.VISIBLE);
            tv_count_three.setText(unreadCount + "");
        }
    }

    private void showAgreeDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_user_agree, null);
        CenterDialog bottomDialog = new CenterDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(false);
        bottomDialog.setCancelable(false);
        bottomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog.show();
        TextView tv_content = dialogView.findViewById(R.id.tv_content);
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        Button bt_agree = dialogView.findViewById(R.id.bt_agree);
        setTextView(tv_content);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
                MyActivity.finishAllActivity(v.getContext());
            }
        });
        bt_agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initApplication();
                initData();
                userInfoPresenter.reqeust("Bearer " + token);
//                getPermission();
                isAgree = true;
                spUtils.putBoolean(SpConstant.USER_AGREE, true);
                bottomDialog.dismiss();
            }
        });
    }

    private void setTextView(TextView tv_content) {
        String str = new String("感谢您使用快帮！在使用快帮前请先阅读并同意《用户协议》和《隐私政策》并遵守相关条款，我们将帮助您收集、使用、存储和共享您个人信息的情况以及您享有的相关权力充分理解各条款内容，特别是免除责任和限制责任的条款等内容，您承诺遵守本协议的全部内容，即产生法律约束力，届时您不应以未阅读本协议的内容或者未获得快帮对您问询的解答等理由主张协议无效要求或撤销本协议。不同意基于快帮平台账户为您提供服务。您需完成平台账户登录才可使用完整服务，如果您未完成账户登录，您将仅可以使用浏览、搜索服务。");
        // SpannableStringBuilder 用法
        SpannableStringBuilder spannableBuilder = new SpannableStringBuilder(str);
        // 单独设置字体颜色
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(getColor(R.color.color_button_red));
        // 单独设置点击事件
        ClickableSpan clickableSpanOne = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString("type", "userAgree");
                intent(UserAgreeActivity.class, bundle);
            }
        };
        spannableBuilder.setSpan(clickableSpanOne, 21, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableBuilder.setSpan( new ForegroundColorSpan(getColor(R.color.color_button_red)), 21, 27, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 单独设置点击事件
        ClickableSpan clickableSpanTwo = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putString("type", "privateAgree");
                intent(UserAgreeActivity.class, bundle);
            }
        };
        spannableBuilder.setSpan(clickableSpanTwo, 28, 34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableBuilder.setSpan( new ForegroundColorSpan(getColor(R.color.color_button_red)), 28, 34, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 不设置点击不生效
        tv_content.setMovementMethod(LinkMovementMethod.getInstance());
        tv_content.setText(spannableBuilder);
    }

    @Override
    protected void destoryData() {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if (checkedId == R.id.home_btn) {
            changeStatusBar(0);
            showFragment(homeFragment);
//            vp_home.setCurrentItem(0);
        } else if (checkedId == R.id.circle_btn) {
            changeStatusBar(1);
//            vp_home.setCurrentItem(1);
            showFragment(squareFragment);
        } else if (checkedId == R.id.cart_btn) {
//            showDialog();
        } else if (checkedId == R.id.chat_btn) {
            if (TextUtils.isEmpty(token)) {
                return;
            }
            changeStatusBar(2);
//            vp_home.setCurrentItem(2);
            showFragment(chatFragment);
//            showFragment(tuiConversationFragment);
        } else if (checkedId == R.id.me_btn) {
            changeStatusBar(3);
//            vp_home.setCurrentItem(3);
            showFragment(meFragment);
        }
    }

    private void showDialog() {
        User loginUser = SpConstant.getLoginUser();
        boolean isIdentity = loginUser.isIdentity();
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_send_order, null);
        BottomDialog bottomDialog = new BottomDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.show();
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        LinearLayout ll_send_order = dialogView.findViewById(R.id.ll_send_order);
        LinearLayout ll_send_order2 = dialogView.findViewById(R.id.ll_send_order2);
        LinearLayout ll_send_dynamic = dialogView.findViewById(R.id.ll_send_dynamic);
        tv_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        ll_send_dynamic.setOnClickListener(v -> {
            intent(SendDynamicActivity.class);
            bottomDialog.dismiss();
        });
        ll_send_order.setOnClickListener(v -> {
            if (isIdentity) {
                intent(ChooseCateActivity.class);
            } else {
                showBindAccount();
            }
            bottomDialog.dismiss();
        });
        ll_send_order2.setOnClickListener(v -> {
//            Bundle bundle = new Bundle();
//            bundle.putString("id","65");
//            intent(PaiDanOrderDetailActivity.class,bundle);
            if (isIdentity) {
                intent(ChooseCate2Activity.class);
            } else {
                showBindAccount();
            }
            bottomDialog.dismiss();
        });
    }

    private void showBindAccount() {
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(MainActivity.this);
        final View dialogView = LayoutInflater.from(MainActivity.this)
                .inflate(R.layout.dialog_bind_account, null);
        normalDialog.setView(dialogView);
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tv_name = dialogView.findViewById(R.id.tv_name);
        TextView tv_sure = dialogView.findViewById(R.id.tv_sure);
        TextView tv_title = dialogView.findViewById(R.id.tv_title);
        tv_name.setText("提示");
        tv_title.setText("完成身份认证即可发布技能");
        tv_sure.setText("去认证");
        AlertDialog alertDialog = normalDialog.create();
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.cancel();
                intent(RealNameActivity.class);
            }
        });
        // 显示
        alertDialog.show();
    }


    /**
     * 展示Fragment
     */
    private void showFragment(Fragment fragment) {
        if (currentFragment != fragment) {
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.hide(currentFragment);
            currentFragment = fragment;
            if (!fragment.isAdded()) {
                transaction.add(R.id.container, fragment).show(fragment).commit();
            } else {
                transaction.show(fragment).commit();
            }
        }
    }

    class UserInfoCall extends SpUserInfoCall {

        @Override
        public void success(User data, Object... args) {
            super.success(data,args);
            mid = data.getId();
            headUrl = data.getImgUrl();
            spUtils.putBoolean(SpConstant.VIP, data.isVip());
            spUtils.putString(SpConstant.FIRST_NAME, data.getFirstName());
            spUtils.putString(SpConstant.NICK_NAME, data.getNickName());
            spUtils.putLong(SpConstant.USER_MID, data.getId());
            spUtils.putString(SpConstant.WX_ID, data.getWxOpenId());
            spUtils.putString(SpConstant.ZFB_ID, data.getZfbOpenId());
            spUtils.putInt(SpConstant.AUTOID, data.getAutoId());
            loginWeChat(data);
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    private void loginWeChat(User data) {
        TUILogin.init(this, 1400572052, null, null);//初始化im
        chatFragment = new ChatFragment();
        TUILogin.login(mid + "", userSig, new V2TIMCallback() {
            @Override
            public void onError(final int code, final String desc) {
                Log.i("answer", "聊天登录失败" + desc + "code=" + code);
                if (code == 6206) {
                    loginWeChat(data);
                }
            }

            @Override
            public void onSuccess() {
                Log.i("answer", "聊天登录成功");
                getImMessagePresenter.reqeust("Bearer " + token);
                getImUnreadPresenter.reqeust("Bearer " + token);
                V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
                    @Override
                    public void onRecvNewMessage(V2TIMMessage msg) {
                        super.onRecvNewMessage(msg);
                        try {
                            Log.i("answer", "获取新消息：" + msg.getMsgID() + msg.getTextElem().getText());
                            //do something takes long time in the work-thread
                            if (!msg.getTextElem().getText().equals("新的交易评价在这里") && !msg.getTextElem().getText().equals("关于行为规范") && !msg.getTextElem().getText().equals("动态圈子讨论区")) {
                                NotificationManagerUtils.startNotificationManager(msg.getNickName(), R.mipmap.logo, MainActivity.this, msg.getTextElem().getText());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
        setAlias(mid + "");
    }

    class VersionCall implements DataCall<AppVersion> {

        @Override
        public void success(AppVersion data, Object... args) {
            String version = data.getVersion();
            String appVersionName = getAppVersionName(MainActivity.this);
            boolean isUpdate = StringUtils.compareVersions(version, appVersionName);
            if (isUpdate) {
                showUpdateDialog(data);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    /*
    获取未读消息总数
     */
    class ImUnreadCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
            Log.i("answer", "获取未读消息数量：" + data);
            if (TextUtils.isEmpty(data) || data.equals("0")) {
                tv_count_three.setVisibility(View.GONE);
            } else {
                tv_count_three.setVisibility(View.VISIBLE);
                tv_count_three.setText(data);
            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }

    /*
 获取未读消息总数
  */
    class ImMessageCall implements DataCall<String> {

        @Override
        public void success(String data, Object... args) {
//            Log.i("answer", "获取未读消息数量：" + data);
//            if (TextUtils.isEmpty(data)) {
//                tv_count_three.setVisibility(View.GONE);
//            } else {
//                tv_count_three.setVisibility(View.VISIBLE);
//                tv_count_three.setText(data);
//            }
        }

        @Override
        public void fail(ApiException e, Object... args) {
        }
    }


    private void showUpdateDialog(AppVersion data) {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_upadate, null);
        bottomDialog = new CenterDialog(this);
        bottomDialog.setContentView(dialogView);
        bottomDialog.setCanceledOnTouchOutside(false);
        //设置点击返回键不消失
        bottomDialog.setCancelable(false);
        bottomDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog.show();
        Button bt_cancel = dialogView.findViewById(R.id.bt_cancel);
        TextView tv_version = dialogView.findViewById(R.id.tv_version);
        TextView tv_content = dialogView.findViewById(R.id.tv_content);
        tv_updating = dialogView.findViewById(R.id.tv_updating);
        LinearLayout ll_update = dialogView.findViewById(R.id.ll_update);
        Button bt_update_two = dialogView.findViewById(R.id.bt_update_two);
        Button bt_update = dialogView.findViewById(R.id.bt_update);
        progress_bar = dialogView.findViewById(R.id.progress_bar);
        tv_version.setText(data.getVersion());
        tv_content.setText(data.getUpgradeDesc());
        String ifForceUpgrade = data.getIfForceUpgrade();
        String downloadUrl = data.getDownloadUrl();

        if (ifForceUpgrade.equals("1")) {
            //强制更新
            ll_update.setVisibility(View.GONE);
            bt_update.setVisibility(View.VISIBLE);
            bottomDialog.findViewById(R.id.layout_update).setVisibility(View.GONE);
            tv_updating.setVisibility(View.VISIBLE);
            downloadAPK(downloadUrl);
        }
//        else {
//            //不强制更新
//            bt_update.setVisibility(View.GONE);
//            ll_update.setVisibility(View.VISIBLE);
//        }

        bt_cancel.setOnClickListener(v -> bottomDialog.dismiss());
        bt_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bt_update.setVisibility(View.GONE);
                ll_update.setVisibility(View.GONE);
                progress_bar.setVisibility(View.VISIBLE);
                downloadAPK(downloadUrl);
            }
        });
        bt_update_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bt_update.setVisibility(View.GONE);
                ll_update.setVisibility(View.GONE);
                progress_bar.setVisibility(View.VISIBLE);
                downloadAPK(downloadUrl);
            }
        });
    }

    //  进度
    private int mProgress;
    //  文件保存路径
    private File apkFile;

    /**
     * 下载APk
     *
     * @param apk_file_url
     */
    private void downloadAPK(final String apk_file_url) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 下载文件
                    HttpURLConnection conn = (HttpURLConnection) new URL(apk_file_url).openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    int length = conn.getContentLength();

                    apkFile = new File(getExternalFilesDir("file"), getAppVersionName(MainActivity.this));
                    FileOutputStream fos = new FileOutputStream(apkFile);

                    int count = 0;
                    byte[] buffer = new byte[512];
                    int len;
                    while ((len = is.read(buffer)) != -1) {
                        count += len;
                        fos.write(buffer, 0, len);
                        // 计算进度条的当前位置
                        mProgress = (int) (((float) count / length) * 100);
                        // 更新进度条
                        mUpdateProgressHandler.sendEmptyMessage(1);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                    // 下载完成
                    mUpdateProgressHandler.sendEmptyMessage(2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 返回当前程序版本名称
     */

    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo("com.example.peibei", 0);
            versionName = pi.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }

        } catch (Exception e) {
        }
        return versionName;
    }

    @SuppressLint("HandlerLeak")
    private Handler mUpdateProgressHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    // 设置进度条
                    progress_bar.setProgress(mProgress);
                    tv_updating.setText(String.format("更新中... %d",mProgress)+"%");
                    break;
                case 2:
                    // 隐藏当前下载对话框
                    bottomDialog.dismiss();
                    // 安装 APK 文件
                    installAPK();
            }
        }
    };

    /**
     * 安装Apk
     */
    private void installAPK() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //兼容android7.0以上版本
        Uri uri = Uri.fromFile(apkFile);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            uri = FileProvider.getUriForFile(this, getPackageName()+".fileProvider", apkFile);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        }
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        startActivity(intent);
    }



    // 这是来自 JPush Example 的设置别名的 Activity 里的代码。一般 App 的设置的调用入口，在任何方便的地方调用都可以。
    private void setAlias(String mid) {
        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, mid));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    Log.i("answer", "设置别名成功+" + mid);
                    getUnReadMessage();//获取未读消息数
                    break;
                case 6002:
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    Log.i("answer", "设置别名失败+" + mid);
                    break;
                default:
            }
        }
    };
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    // 调用 JPush 接口来设置别名。
                    JPushInterface.setAliasAndTags(getApplicationContext(),
                            (String) msg.obj,
                            null,
                            mAliasCallback);
                    break;
                default:
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //2秒内按两次退出
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                UIUtils.showToastSafe(R.string.press_again_exit);
                exitTime = System.currentTimeMillis();
            } else {
                MyActivity.finishAllActivity(this);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void changeStatusBar(int tabPosition) {
        switch (tabPosition) {
            case 0:
                ImmersionBar.with(this)
                        .fitsSystemWindows(false)
                        .statusBarColor(R.color.home_red)
                        .statusBarDarkFont(false)
                        .hideBar(BarHide.FLAG_SHOW_BAR)
                        .init();
                break;
            case 3:
                ImmersionBar.with(this)
                        .fitsSystemWindows(false)
                        .statusBarColor(android.R.color.transparent)
                        .statusBarDarkFont(false)
                        .hideBar(BarHide.FLAG_SHOW_BAR)
                        .init();
                break;
            case 1:
            case 2:
                ImmersionBar.with(this)
                        .fitsSystemWindows(true)
                        .statusBarColor(R.color.white)
                        .statusBarDarkFont(true)
                        .hideBar(BarHide.FLAG_SHOW_BAR)
                        .init();
                break;
//            case 3:
//                ImmersionBar.with(this)
//                        .fitsSystemWindows(false)
//                        .statusBarColor(R.color.white)
//                        .statusBarDarkFont(true)
//                        .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
//                        .init();
//                break;
        }
    }


}
